package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bizmq.BiMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.CosManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 图表接口
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;
    @Resource
    private CosManager cosManager;
    @Resource
    private AiManager aiManager;
    @Resource
    private RedisLimiterManager redisLimiterManager;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private BiMessageProducer biMessageProducer;


    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @ApiOperation("添加图表")
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation("删除图表")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @ApiOperation("更新（仅管理员）图表")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);

        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @ApiOperation("获取图表信息")
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }
    //getQueryWrapper方法


    /**
     * 智能分析(MQ)
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String chartName = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(StringUtils.isAnyBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartType) && chartType.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(ObjectUtils.isEmpty(multipartFile), ErrorCode.PARAMS_ERROR, "传入文件为空");
        //限流判断，每个用户定义一个限流器
        redisLimiterManager.doRateLimiter("genChartByAi_" + loginUser.getId());
        //获取文件大小并校验
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_MB, ErrorCode.PARAMS_ERROR, "传入文件过大超过1M");
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffix = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "传入文件后缀非法");

        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String finalGoal = goal + " " + "图表类型请用:" + chartType;
        userInput.append(finalGoal).append("\n");
        String csvData = ExcelUtils.ExceltoCsv(multipartFile);
        userInput.append("表格数据：").append(csvData).append("\n");

        Chart chart = new Chart();
        chart.setName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        Long newCharId = chart.getId();
        biMessageProducer.sendMessage(String.valueOf(newCharId));
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(newCharId);
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析(异步)
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String chartName = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        //根据request快速获取用户信息
        User loginUser = userService.getLoginUser(request);
        //校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartType) && chartType.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(ObjectUtils.isEmpty(multipartFile), ErrorCode.PARAMS_ERROR, "传入文件为空");
        //限流判断，每个用户定义一个限流器
        redisLimiterManager.doRateLimiter("genChartByAi_" + loginUser.getId());
        //获取文件大小并校验
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_MB, ErrorCode.PARAMS_ERROR, "传入文件过大超过1M");
        //获取文件后缀名
        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件后缀
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        //定义白名单
        final List<String> validFileSuffix = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "传入文件后缀非法");
        //分析需求:
        // 分析网站用户的增长情况
        // 原始数据:
        // 日期，用户数
        // 1号，10
        // 2号，20
        // 3号，30
        //用户输入目标,图表的类型,图表数据
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String finalGoal = goal + " " + "图表类型请用:" + chartType;
        userInput.append(finalGoal).append("\n");
        //压缩后的数据
        String csvData = ExcelUtils.ExceltoCsv(multipartFile);
        userInput.append("表格数据：").append(csvData).append("\n");
        //把响应的数据存到数据库
        Chart chart = new Chart();
        chart.setName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
//        chart.setGenChart(genChart);
//        chart.setGenResult(genResult);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");


        //（执行异步）
        CompletableFuture.runAsync(() -> {
            //更新执行状态为运行状态
            Chart chartRunning = new Chart();
            chartRunning.setId(chart.getId());
            chartRunning.setStatus("running");
            boolean updateRunningResult = chartService.updateById(chartRunning);
            if (!updateRunningResult) {
                handleChartUpdateError(chart.getId(), "更新执行状态为运行状态-失败！");
                return;
            }
            //调用AI根据输入得到ai返回的结果
            String aiManagerResult = aiManager.doChat(CommonConstant.biModel, userInput.toString());
            //aiManagerResult返回的数据有【【【【【作为分隔符.
            String[] splits = aiManagerResult.split("【【【【【");
            if (splits.length < 3) {
//                throw new BusinessException(ErrorCode.PARAMS_ERROR, "AI生成错误");
                handleChartUpdateError(chart.getId(), "AI生成错误");
                return;
            }
            String genChart = splits[1].trim();
            String genResult = splits[2].trim();
            //更新执行状态为成功状态,并ai生成的图表 和 结论添加到数据库。
            Chart chartSucceed = new Chart();
            chartSucceed.setId(chart.getId());
            chartSucceed.setStatus("succeed");
            chartSucceed.setGenChart(genChart);
            chartSucceed.setGenResult(genResult);
            boolean updateSuccedResult = chartService.updateById(chartSucceed);
            if (!updateSuccedResult) {
                handleChartUpdateError(chart.getId(), "更新执行状态为成功状态-失败！");
            }
        }, threadPoolExecutor);
        BiResponse biResponse = new BiResponse();
        //biResponse.setGenChart(genChart);
        //biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }


    //    (同步)
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile, GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String chartName = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        //根据request快速获取用户信息
        User loginUser = userService.getLoginUser(request);
        //校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(StringUtils.isAnyBlank(chartType) && chartType.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称为空或长度超过100");
        ThrowUtils.throwIf(ObjectUtils.isEmpty(multipartFile), ErrorCode.PARAMS_ERROR, "传入文件为空");
        //限流判断，每个用户定义一个限流器
        redisLimiterManager.doRateLimiter("genChartByAi_" + loginUser.getId());
        //获取文件大小并校验
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_MB, ErrorCode.PARAMS_ERROR, "传入文件过大超过1M");
        //获取文件后缀名
        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件后缀
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        //定义白名单
        final List<String> validFileSuffix = Arrays.asList("xls", "xlsx");
        ThrowUtils.throwIf(!validFileSuffix.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "传入文件后缀非法");
        //分析需求:
        // 分析网站用户的增长情况
        // 原始数据:
        // 日期，用户数
        // 1号，10
        // 2号，20
        // 3号，30
        //用户输入目标,图表的类型,图表数据
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String finalGoal = goal + " " + "图表类型请用:" + chartType;
        userInput.append(finalGoal).append("\n");
        //压缩后的数据
        String csvData = ExcelUtils.ExceltoCsv(multipartFile);
        userInput.append("表格数据：").append(csvData).append("\n");

        //AI根据输入得到ai返回的结果
        final long biModel = 1659171950288818178L;
        String aiManagerResult = aiManager.doChat(biModel, userInput.toString());
        //aiManagerResult返回的数据有【【【【【作为分隔符.
        String[] splits = aiManagerResult.split("【【【【【");
        if (splits.length < 3) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "AI生成错误");
        }
        BiResponse biResponse = new BiResponse();
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        //把响应的数据存到数据库
        Chart chart = new Chart();
        chart.setName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }
    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    //处理错误类
    private void handleChartUpdateError(long chartId, String executeMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(executeMessage);
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult) {
            log.error("更新状态为成功状态失败。失败图表编号为：" + chartId
                    + "错误信息为:" + executeMessage);
        }
    }
}




